package com.ftp.web.spider.service.nettyclinet;



import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.security.core.parameters.P;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;


public class NettyFileClinetHandler extends ChannelInboundHandlerAdapter  {

    public RandomAccessFile randomAccessFile;

    public File mediaFile;

    public NettyFileClinetHandler(File ef) {
        if (ef.exists()) {
            if (!ef.isFile()) {
                System.out.println("Not a file :" + ef);
                return;
            }else {
                mediaFile=ef;
            }
        }
    }

    //首次触发
    public void channelActive(ChannelHandlerContext ctx) {
        try {
            randomAccessFile = new RandomAccessFile(mediaFile, "r");
            byte[] bytes=new byte[102400];
            randomAccessFile.seek(0);
            if ( randomAccessFile.read(bytes) != -1) {
                ctx.writeAndFlush(bytes);
            } else {
                System.out.println("文件已经读完");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        Object o=msg;
        byte[] bytes=new byte[1024000];
        if (msg instanceof Long) {
            try {
                //随机读取文件
                randomAccessFile = new RandomAccessFile(mediaFile, "r");
                //设定文件读取位置
                randomAccessFile.seek((long)msg);
                //向channel中写入读取的byte
                randomAccessFile.read(bytes);
                long s=randomAccessFile.getFilePointer();
                Long fileTotalSize=mediaFile.length();
                Long putSize=(Long)msg+bytes.length;
                if(putSize<fileTotalSize){
                    ctx.writeAndFlush(bytes);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                randomAccessFile.close();
            }
        }
    }


    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


}
